<template>
  <div class="week-select">
    <van-cell
      is-link
      title="所属周"
      :value="showValue"
      @click="openTimePicker"
    />
    <van-cell
      title="日期范围"
      :value="showRange"
    />
    <van-calendar
      v-model="showTimePicker"
      @confirm="onConfirm"
      :default-date="currentDate"
      :min-date="new Date('2020-01-01')"
      :max-date="new Date('2100-01-01')"
      :first-day-of-week="1"
    />
  </div>
</template>

<script>
import dayjs from "dayjs";

export default {
  name: "WeekSelect",
  props: {
    value: {
      type: String,
      default: "",
    },
  },
  model: {
    prop: "value",
    event: "change",
  },
  computed: {
    showValue() {
      if (!this.value) return "请选择";
      let val = this.value;
      return `${val.slice(0, 4)}-${val.slice(4, 6)}第${parseInt(
        val.slice(6, 8)
      )}周`;
    },
    showRange() {
      if (!this.value) return "请选择";
      let date = this.getValueWeek(this.value);
      if (!date) return "请选择";
      return `${date.start}~${date.end}`;
    },
  },
  data() {
    return {
      dayjs,
      showTimePicker: false,
      currentDate: new Date(),
    };
  },
  methods: {
    onConfirm(val) {
      let year = val.getFullYear();
      let time = val.getTime();
      let all = this.libs.week(year);
      let week = all.find((item) => {
        return time >= item.startTime && time <= item.endTime;
      });

      let month = week.month > 9 ? week.month : "0" + week.month;
      let weekNum =
        week.weekInMonth > 9 ? week.weekInMonth : "0" + week.weekInMonth;
      let value = `${week.year}${month}${weekNum}`;
      this.$emit("change", value);

      this.showTimePicker = false;
    },
    getValueWeek(value) {
      let year = parseInt(value.slice(0, 4));
      let month = parseInt(value.slice(4, 6));
      let week = parseInt(value.slice(6, 8));

      let all = this.libs.week(year);
      let date = all.find(
        (item) =>
          item.year === year &&
          item.month === month &&
          item.weekInMonth === week
      );
      return date;
    },
    openTimePicker() {
      if (this.value) {
        let date = this.getValueWeek(this.value);
        // 生成时间
        this.currentDate = date ? new Date(date.start) : new Date();
      } else {
        this.currentDate = new Date();
      }
      this.showTimePicker = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.week-select {
}
</style>
